package com.sky.wsp.mybatis.plus.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sky.wsp.mybatis.plus.dao.ProjectItemMapper;
import com.sky.wsp.mybatis.plus.dao.entity.ProjectItemEntity;
import com.sky.wsp.mybatis.plus.dao.vo.TaskProgressVO;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

/**
 * @desccription 任务开发进度-控制器
 * @auth wangshaopeng@talkweb.com.cn
 * @date 2023/5/5
 */
@RestController
@RequestMapping("/task-progress")
public class TaskProgressController {
    private static final Map<String, String> userMap = new HashMap<>();

    @Resource
    private ProjectItemMapper projectItemMapper;


    @GetMapping(name = "按【开发人员->任务列表】组织成的树", value = "/tree")
    public TaskProgressVO tree(String sprintId) {
        TaskProgressVO root = new TaskProgressVO();
        root.setId(null);
        root.setLeafCount(0);
        root.setWorkDay(0);
        root.setCompleteDay(0);
        root.setChildren(new ArrayList<>());

        if (StrUtil.isBlank(sprintId)) {
            return root;
        }

//        sprintId = "1651110449385545729";
        List<ProjectItemEntity> itemList = loadItem(sprintId);
        if (CollectionUtil.isEmpty(itemList)) {
            return root;
        }

        createTree(root, itemList);

        // 打印结果
        printWork(root);
        return root;
    }

    /**
     * 测试用-打印日志
     *
     * @param root
     */
    private void printWork(TaskProgressVO root) {
        System.out.println(root);
        List<TaskProgressVO> children = root.getChildren();
        if (null != children && !children.isEmpty()) {
            for (TaskProgressVO child : children) {
                printWork(child);
            }
        }
    }

    /**
     * 查询迭代下的所有叶子任务
     *
     * @param sprintId
     * @return
     */
    private List<ProjectItemEntity> loadItem(String sprintId) {
        LambdaQueryWrapper<ProjectItemEntity> query = new LambdaQueryWrapper<>();
        query.select(
                ProjectItemEntity::getId,
                ProjectItemEntity::getItemCode,
                ProjectItemEntity::getItemType,
                ProjectItemEntity::getParentId,
                ProjectItemEntity::getTitle,
                ProjectItemEntity::getHandledBy,
                ProjectItemEntity::getStartTime,
                ProjectItemEntity::getEndTime,
                ProjectItemEntity::getStatus,
                ProjectItemEntity::getLeafFlag);
        query.eq(ProjectItemEntity::getSprintId, sprintId);
        query.eq(ProjectItemEntity::getDelFlag, false);
//        query.eq(ProjectItemEntity::getItemType, "bug");
        query.ne(ProjectItemEntity::getItemType, "bug");
        List<ProjectItemEntity> projectItemEntities = projectItemMapper.selectList(query);
        return projectItemEntities;
    }

    /**
     * 所有的任务排期，按【开发人员->任务列表】组织成树
     *
     * @param parent
     * @param itemList
     */
    private void createTree(TaskProgressVO parent, List<ProjectItemEntity> itemList) {
        for (ProjectItemEntity item : itemList) {
            if (!StringUtils.equals(parent.getId(), item.getParentId())) {
                continue;
            }
            if ("1655833950407335938".equals(item.getId())
                    || "1655833950407335938".equals(item.getParentId())
            ) {
                System.out.println("==================begin debug");
            }
            TaskProgressVO itemVO = new TaskProgressVO();
            BeanUtils.copyProperties(item, itemVO);
            itemVO.setLeafCount(1);
            // 叶子节点的任务，才进行进度估算
            if (("task".equals(item.getItemType()) || "bug".equals(item.getItemType())) &&
                    null != item.getLeafFlag() && item.getLeafFlag()) {
                Date startTime = item.getStartTime();
                Date endTime = item.getEndTime();
                Integer workDay = 0;
                if (null != startTime && null != endTime) {
                    // TODO 估时可能跨周末、节假日，暂不考虑
                    Long diff = DateUtil.betweenDay(startTime, endTime, true) + 1;
                    workDay = diff.intValue();
                }
                itemVO.setWorkDay(workDay);
                // TODO 任务状态，是在数据库进行配置的（devops_project_item_status_config）
                if ("TASK_PENDING".equals(item.getStatus()) || "BUG_PENDING".equals(item.getStatus())) {
                    // 待处理，进度0%
                    itemVO.setCompleteDay(0);
                } else if ("TASK_PROCESSING".equals(item.getStatus()) || "BUG_PROCESSING".equals(item.getStatus())) {
                    // 处理中，进度50%
                    itemVO.setCompleteDay(workDay / 2);
                } else if ("BUG_TOBEVERIFIED".equals(item.getStatus())) {
                    // BUG 待验证，进度75%
                    itemVO.setCompleteDay(workDay * 3 / 4);
                } else {
                    // 已取消TASK_CANCELED、已完成TASK_FINISHED、已关闭BUG_CLOSED，进度100%
                    itemVO.setCompleteDay(workDay);
                }
            } else {
                itemVO.setLeafCount(0);
                itemVO.setWorkDay(0);
                itemVO.setCompleteDay(0);
                itemVO.setChildren(new ArrayList<>());
                // 迭代处理子树
                createTree(itemVO, itemList);
            }
            parent.getChildren().add(itemVO);
            parent.setLeafCount(parent.getLeafCount() + itemVO.getLeafCount());
            parent.setWorkDay(parent.getWorkDay() + itemVO.getWorkDay());
            parent.setCompleteDay(parent.getCompleteDay() + itemVO.getCompleteDay());
        }
    }
}
